<template>
  <div class="login-container">
    <h2 class="login-title">登录</h2>
    <form @submit.prevent="handleLogin" class="login-form">
      <div class="form-group">
        <label for="username">用户名</label>
        <input
          type="text"
          id="username"
          v-model="username"
          required
          placeholder="请输入用户名"
        />
      </div>
      <div class="form-group">
        <label for="password">密码</label>
        <input
          type="password"
          id="password"
          v-model="password"
          required
          placeholder="请输入密码"
        />
      </div>
      <div class="form-group">
        <button type="submit" :disabled="isSubmitting">登录</button>
      </div>
    </form>
  </div>
</template>

<script setup lang="ts">
import { onUnmounted, ref } from "vue";
import { useRouter } from "vue-router";

// 定义响应式数据
const username = ref<string>("");
const password = ref<string>("");
const isSubmitting = ref<boolean>(false);

// 获取路由实例
const router = useRouter();
// 将 timer 定义为组件的顶层变量
let timer: number | undefined;
// 登录处理逻辑
const handleLogin = () => {
  // 基本验证
  if (!username.value.trim() || !password.value.trim()) {
    alert("用户名和密码不能为空！");
    return;
  }

  isSubmitting.value = true;

  // 模拟登录请求
    timer = setTimeout(() => {
    isSubmitting.value = false;
    // 存放用户toke到浏览器的本地
    localStorage.setItem('token', 'ysy')
    router.push("/home"); // 假设登录后跳转到 /dashboard
  }, 1500);
};
onUnmounted(()=> {
  clearTimeout(timer);
})
</script>

<style scoped>
.login-container {
  max-width: 400px;
  margin: 50px auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 8px;
  background-color: #f9f9f9;
}

.login-title {
  text-align: center;
  margin-bottom: 20px;
}

.login-form {
  display: flex;
  flex-direction: column;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
}

.form-group input {
  width: 100%;
  padding: 8px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.form-group button {
  width: 100%;
  padding: 10px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.form-group button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}
</style>
